package com.crazy.util.lock.wait;

import java.util.concurrent.TimeUnit;

/**
 * @author panyonghui
 * @describe synchronized中等待和唤醒线程示例
 * @date 2022/1/13 10:34
 */
public class Demo1 {
    private static Object object = new Object();
    static class Th extends Thread{
        @Override
        public void run() {
            System.out.println(this.getName() + "准备获取锁");
            synchronized(object){
                try {
                    System.out.println(this.getName() + "获取到锁，让出资源进行等待");
                    object.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(this.getName() + "准备释放锁");
            }
            System.out.println(this.getName() + "执行结束，释放锁");
        }
    }

    static class Th2 extends Thread{
        @Override
        public void run() {
            System.out.println(this.getName() + "准备获取锁");
            synchronized(object){
                System.out.println(this.getName() + "获取到锁，唤醒等待线程");
                object.notify();
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(this.getName() + "准备释放锁");
            }
            System.out.println(this.getName() + "执行结束，释放锁");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Th th = new Th();
        th.setName("T1");
        Th2 th2 = new Th2();
        th2.setName("T2");
        th.start();
        TimeUnit.SECONDS.sleep(3);
        th2.start();
    }
}
